package com.anjiplus.template.gaea.business.modules.push.template.service.impl;

import com.alibaba.fastjson.JSON;
import com.anji.plus.gaea.bean.ResponseBean;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anji.plus.gaea.push.domain.po.TemplatePO;
import com.anji.plus.gaea.push.enums.PushEnum;
import com.anji.plus.gaea.push.support.AbstractPushSender;
import com.anji.plus.gaea.push.type.base.BasePushDetails;
import com.anji.plus.gaea.push.utils.PushContextConvertUtils;
import com.anji.plus.gaea.push.utils.TemplateAnalysisUtil;
import com.anji.plus.gaea.utils.ApplicationContextUtils;
import com.anji.plus.gaea.utils.GaeaBeanUtils;
import com.anjiplus.template.gaea.business.code.ResponseCode;
import com.anjiplus.template.gaea.business.feign.AuthServiceClient;
import com.anjiplus.template.gaea.business.feign.dto.AppspPushParam;
import com.anjiplus.template.gaea.business.modules.push.template.controller.dto.GaeaPushTemplateDTO;
import com.anji.plus.gaea.push.type.param.PushParamVO;
import com.anjiplus.template.gaea.business.modules.push.template.dao.GaeaPushTemplateMapper;
import com.anjiplus.template.gaea.business.modules.push.template.dao.entity.GaeaPushTemplate;
import com.anjiplus.template.gaea.business.modules.push.template.service.GaeaPushTemplateService;

import com.anjiplus.template.gaea.common.RespCommonCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * (GaeaPushTemplate)ServiceImpl
 *
 * @author lr
 * @since 2021-02-08 09:36:40
 */
@Service
@Slf4j
public class GaeaPushTemplateServiceImpl implements GaeaPushTemplateService {
    @Autowired
    private GaeaPushTemplateMapper gaeaPushTemplateMapper;

    @Override
    public GaeaBaseMapper<GaeaPushTemplate> getMapper() {
        return gaeaPushTemplateMapper;
    }

    @Autowired
    private AuthServiceClient authServiceClient;
    /**
     * 预览
     *
     * @return
     */
    @Override
    public ResponseBean preViewTemplate(GaeaPushTemplateDTO templateVO) {
        if (templateVO.getId() != null) {
            GaeaPushTemplate gaeaPushTemplate = selectOne(templateVO.getId());
            GaeaBeanUtils.copyAndFormatter(gaeaPushTemplate, templateVO);
        }
        boolean ismail = (templateVO.getTemplateType() != null && templateVO.getTemplateType().toLowerCase().equals("mail")) ? false : true;
        TemplatePO templatePO = TemplateAnalysisUtil.analysisTemplate(templateVO.getTemplateShow(), true, ismail);
        Map<String, Object> param = TemplateAnalysisUtil.getPreParam(templatePO.getParamMap());
        /*String html = TemplateAnalysisUtil.buildHTML(templatePO, param, templatePO.getParamMap(),
                templateVO.getTemplateType().toLowerCase().equals("mail"));
        if (templateVO.getTemplateType().toLowerCase().equals("dingtalk")) {
            templatePO.setHtml(html.replace("\n", "</br>"));
        } else {
            templatePO.setHtml(html);
        }*/
        templatePO.setParamMap(TemplateAnalysisUtil.conversionParaMap(templatePO.getParamMap()));
        return ResponseBean.builder().data(templatePO).build();
    }


    /**
     * 消息推送测试
     * 使用策略模式，根据请求类型  调用不同的推送处理器
     *
     * @param requestModel
     */
    @Override
    public ResponseBean testSendPush(PushParamVO requestModel) throws Exception {
        // 读取模板
        GaeaPushTemplate gaeaPushTemplate = this.selectOne("template_code", requestModel.getTemplateCode());
        if("appsp".equals(requestModel.getPushType())){
            if(StringUtils.isEmpty(requestModel.getTo())){
                return ResponseBean.builder().code(RespCommonCode.RECEIVER_IS_EMPTY).build();
            }
            String[] toArr=requestModel.getTo().split(",");
            List<String> userList=Arrays.asList(toArr);
            //app端推送
            AppspPushParam pushParam=new AppspPushParam();
            pushParam.setTitle(StringUtils.isNotEmpty(requestModel.getSubject())?requestModel.getSubject():"test appsp push");
            String convert = PushContextConvertUtils.convertList(gaeaPushTemplate.getTemplateShow(), requestModel.getParamMap());
            log.info("--appsp send content--{}",convert);
            pushParam.setContent(convert);
            pushParam.setUsernames(userList);
            ResponseBean responseBean= authServiceClient.testAppspPush(pushParam);
            log.info("--appsp send result--{}", JSON.toJSONString(responseBean));
            return responseBean;
        }
        Class classByType = PushEnum.getClassByType(requestModel.getPushType());
        AbstractPushSender abstractPushSender;
        try {
            abstractPushSender = (AbstractPushSender) ApplicationContextUtils.getBean(classByType);
        } catch (Exception e){
            throw BusinessExceptionBuilder.build(ResponseCode.COMPONENT_NOT_LOAD, "push");
        }
         // 解析模板
        String template = gaeaPushTemplate.getTemplate();
        Map paramMap = requestModel.getParamMap();
        String convert = PushContextConvertUtils.convertList(template, paramMap);
        requestModel.setParam(convert);
        BasePushDetails pushDetails = abstractPushSender.convert(requestModel);
        abstractPushSender.doSend(pushDetails);
        return ResponseBean.builder().build();
    }
}
